package com.iot.geteway.filters;

import com.iot.geteway.cache.BlackIpCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author 咕唧
 * @Date 2022/7/21 20:30
 * @Version 1.0
 * 自定义全局过滤器
 */
@Component
public class BlackIpGloablFilter implements GlobalFilter, Ordered {

    private BlackIpCache blackIpCache;

    @Autowired
    public void setBlackIpCache(BlackIpCache blackIpCache) {
        this.blackIpCache = blackIpCache;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String remoteIp = exchange.getRequest().getRemoteAddress().getHostString();


        return Mono.just(blackIpCache.getBlackIpSet())
                .filter(collection -> !collection.contains(remoteIp))
                .map(r -> chain.filter(exchange))
                .defaultIfEmpty(exchange.getResponse()
                        .writeAndFlushWith(Mono.just(Mono.just(DefaultDataBufferFactory.sharedInstance.allocateBuffer().write("当前ip不允许访问".getBytes(StandardCharsets.UTF_8))))))
                .flatMap(r -> r);
    }

    @Override
    public int getOrder() {
        return -10;
    }
}
